/**
 * 
 * @authors youzhao.zhou@pandauu.com
 * @date    2016-09-21 12:45:33
 * @version $Id$
 * 依赖于DOM操作库
 * 发送信息模块实现：
 *          1. 文字发送按钮功能
 *                输入框有文字时显示发送按钮，没有文字时隐藏按钮
 *                将文字信息发送到后台
 *                对URL特殊处理
 * 
 *          2. 发送图片功能
 *                利用H5的fileReader功能将图片保存base64
 *                通过formData功能将图片上传到后台服务器
 *                
 * 
 */

;(function(root,factory){

  if(typeof exports === 'object' && typeof module === 'object'){
    
    factory(exports,typeof exports !== 'undefined' ? require('./zepto.js')&&root.$ : root.$, require('../../public_src/js/1_self/3_log.js'), require('../../public_src/js/1_self/2_config.js'), typeof exports !== 'undefined' ? require('../../public_src/js/underscore/underscore.js') : root._);

  } else if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(['exports', './zepto.js', '../../public_src/js/1_self/3_log.js', '../../public_src/js/1_self/2_config.js', '../../public_src/js/underscore/underscore.js'], factory);
  } else if (typeof exports === 'object' && typeof exports.nodeName !== 'string') {
    // CommonJS
    factory(exports, typeof exports !== 'undefined' ? require('./zepto.js')&&root.$ : root.$, require('../../public_src/js/1_self/3_log.js'), require('../../public_src/js/1_self/2_config.js'), typeof exports !== 'undefined' ? require('../../public_src/js/underscore/underscore.js') : root._);
  } else {
    // Browser globals
    factory({}, root.$, root.log, root.conf, root._);
  }
})(typeof window !== 'undefined' ? window : this ,function(exports, $, log, conf, _, undefined){
  'use strict';

  /*
    调试开关
  */
  log._logToggle(true);

  log._log(conf);
  var urlConf = conf._conf;

  /*
    发送按钮显示事件
    sendMsgBtnWidth 中 100 为发送按钮的宽度， 750 为设计图宽度
  
  */
  var sendMsgBtnWidth = 100/750;
  var htmlFontSize = parseFloat($('html').css('fontSize'));

  var msgInuptDom = $('.jsSendInput');
  var sentBtnDom = $('.jsSendBtn');

  msgInuptDom.bind('input', function(event) {
    /* Act on the event */
    var size = sendMsgBtnWidth*htmlFontSize;
    if ($(this).val()) {
      if (sentBtnDom.hasClass('s-hide')) {
        $(this).css({
          width : ($(this).width()-size) / htmlFontSize + 'rem'
        });

        sentBtnDom.removeClass('s-hide');
        sentBtnDom.css({
          width: sendMsgBtnWidth + 'rem'
        });
      }
    }else{
      $(this).css({
        width : ($(this).width()+size) / htmlFontSize + 'rem'
      });

      sentBtnDom.addClass('s-hide');
    }

  });

  $('.jsSendMsg').on('click', function(event) {
    

    /*
      事件委托
        根据HTML data-event属性判断哪个节点触发事件
        值：
          input   ---   input框触发事件
          img     ---   图片上传按钮
          msg     ---   发送信息
    */

    /* Act on the event */
    var target = $(event.target);
    var eventTarget = $(event.target).data('event');

    switch(eventTarget){
      case 'img':
        $(event.target).unbind('change').bind('change', function(e) {
          /* Act on the event */
          if (typeof FileReader === 'undefined'||typeof FormData === 'undefined') {
            alert('您的浏览器暂不支持图片上传，请更换浏览器！');

            return false;
          }

          var self = this;

          var imgForm = new FormData();

          imgForm.append('imageFile',self.files[0]);

          imgAjax({
            url: urlConf.apiRoot + urlConf.apiPre.one + urlConf.api.upload,
            type: 'POST',
            data: imgForm,
            success: function(data){
              log._log(data);

              if (data.code === 0) {
                sendImgInfo(data.path);
                
              }else{
                $('#fail').removeClass('s-hide');
                $('.js-warn-content').html(data.msg);
                addCloseEvent('.js-fail');
                log._log(data.msg);
              }
            },
            error: function(error){
              log._log(error);
            }
          });
          
        });
        break;
      case 'msg':
        event.preventDefault();

        sendMsg(
          {
            type: 1,
            content: msgInuptDom.val(),
            thread_id: $('.service').data('id')
          },
          function(data){
            if (data.code === 0 ) {
              // $('#fail').removeClass('s-hide');
              // $('.js-warn-content').html(data.msg);
              // addCloseEvent('.js-fail');

              msgInuptDom.val('');
              msgInuptDom.trigger('input');


              if (data.data.type === '1') {
                data.data.msg = setUrl(data.data.msg);
              }else{
                data.data.msg = e.target.result;
                data.data.thumb = e.target.result;
              }
              var tempData = [];
              tempData.push(data.data);
              log._log(tempData);
              renderMsg(_, tempData);
            }else{
              $('#fail').removeClass('s-hide');
              $('.js-warn-content').html(data.msg);
              addCloseEvent('.js-fail');
            }

          },
          function (data){
            $('#fail').removeClass('s-hide');
            $('.js-warn-content').html('网络连接错误！');
            addCloseEvent('.js-fail');
          }
        );

        break;
      case 'quick':
        /*
          设置导航头部
        */
        $('.middle').html('快捷回复列表');

        var serviceH = $(target.data('target')).height();

        log._log(serviceH);

        $.ajax({
          url: urlConf.apiRoot + urlConf.apiPre.one + urlConf.api.quickReplyList,
          type: 'GET',
          dataType: 'json'
        })
        .done(function(data) {
          if (data.code === 0) {
            $('.jsReplyContainer').html(_.template($('#replyTpl').html())({list: data.data}));
            log._log($('.jsReplyContainer'));
          }
          
        })
        .fail(function() {
          log._log("error");
        })
        .always(function() {
          log._log("complete");
        });

        window.history.pushState('quick','quick','#/quick');


        $(target.data('target')).css({
          'transform': 'translateY(-' + serviceH + 'px)',
          '-webkit-transform': 'translateY(-' + serviceH + 'px)'
        });

        $('.jsQuickreply').css({
          'transform': 'translateY(-' + serviceH + 'px)',
          '-webkit-transform': 'translateY(-' + serviceH + 'px)'
        });
        $('.jsQuickreply').removeClass('s-hide');

        window.addEventListener('popstate',function(){
          $($('.jsQuickreply').data('target')).css({
            'transform': 'inherit',
            '-webkit-transform': 'inherit'
          });

          $('.jsService').css({
            'transform': 'inherit',
            '-webkit-transform': 'inherit'
          });
          $('.jsQuickreply').addClass('s-hide');

          $('body')[0].scrollTop = $('.jsService').height()-$(window).height();
          /*
            设置导航头部
          */
          $('.middle').html('熊猫天下客服');

        });

        removeEvent();
        addEvent();
        
        var selectedDom = null;
        function addEvent(){
          $('.jsQuickreply').on('click', quickOp);
        }
        function removeEvent(){
          $('.jsQuickreply').unbind('click');
        }

        /*
          快捷回复操作
        */
        function quickOp(event){

          event.preventDefault();
          var target = $(event.target);
          var eventType = target.data('event');

          switch(eventType){
            case 'li':
              target.siblings(".select").removeClass('select');
              target.addClass('select');
              selectedDom = target;
              break;
            case 'use':

              if (!selectedDom) {
                alert('请选择快捷回复');

                return false;
              }

              if (selectedDom.data('type') == '1') {
                qSendMsg(msgInuptDom,selectedDom.text().trim());
                msgInuptDom.trigger('input');
                // setTimeout(function(){
                //   $('body')[0].scrollTop = $('.jsService').height();
                // },0);
              }else{
                sendImg(selectedDom.find('img').attr('src'));
              }

              $(target.data('clear')).removeClass('select');

              $(target.data('target')).css({
                'transform': 'inherit',
                '-webkit-transform': 'inherit'
              });

              $('.jsService').css({
                'transform': 'inherit',
                '-webkit-transform': 'inherit'
              });
              $('.jsQuickreply').addClass('s-hide');

              $('body')[0].scrollTop = $('.jsService').height()-$(window).height();
              /*
                设置导航头部
              */
              $('.middle').html('熊猫天下客服');
              window.history.back();
              break;
          }

        }

        /*
          发送图片
        */
        function sendImg(dataImg){
          sendImgInfo(dataImg);
        }
        /*
          选择文字快捷回复
        */
        function qSendMsg(inputDom, data){
          inputDom.val(data);
        }

        break;
    }
  });
  /*
    上传图片后发送信息到服务器
  */

  function sendImgInfo(dataImg){

    sendMsg(
      {
        type: 2,
        content: dataImg,
        thread_id: $('.service').data('id')
      },
      function(data){
        if (data.code === 0 ) {
          if(!$('.msg img').attr('src')){
            $('.msg img').attr('src',dataImg);
          }

          if (data.data.type === '1') {
            data.data.msg = setUrl(data.data.msg);
          }else{
            data.data.msg = urlConf.root + data.data.msg;
            data.data.thumb = data.data.msg.replace('uploads/kf/','uploads/kf/thumbnail/');
          }
          var tempData = [];
          tempData.push(data.data);
          log._log(tempData);
          renderMsg(_, tempData);

          imgDefer();
          
          $(self).val('');
        }else{
          $('#fail').removeClass('s-hide');
          $('.js-warn-content').html(data.msg);
          addCloseEvent('.js-fail');
        }
      },
      function (data){
        $('#fail').removeClass('s-hide');
        $('.js-warn-content').html('网络连接错误！');
        addCloseEvent('.js-fail');
      }
    );
    
  }
  /*
    发送消息请求
  */
  function sendMsg(data, success, fail){
    $.ajax({
      url: urlConf.apiRoot + urlConf.apiPre.one + urlConf.api.sendToUser,
      type: 'POST',
      dataType: 'json',
      data: data,
    })
    .done(function(data) {
      
      if (typeof success === 'function') {
        success(data);
      }
    })
    .fail(function() {
      if (typeof fail === 'function') {
        fail(data);
      }
    })
    .always(function() {
      log._log("complete");
    });
  }
  /*
    启动弹框关闭按钮
  */
  function addCloseEvent(selector){
    $(selector).unbind('click').bind('click', function(event) {
      /* Act on the event */
      $($(this).data('target')).addClass('s-hide');

      $(selector).unbind('click');
    });
  }
  /*
    H5图片上传
  */
  function imgAjax(options){

    var oReq = new XMLHttpRequest();
    oReq.open(options.type||'', options.url||'');
    oReq.send(options.data||'');

    oReq.onload = function(data){
      log._log(this);
      if (this.readyState===4 && this.status===200) {
        log._log(data);
        if (typeof options.success === 'function') {
          options.success(JSON.parse(data.target.response));
        }
      }else{
        if (typeof options.error === 'function') {
          options.error(data.target.response);
        }
      }
    };
  }
  /*
    渲染消息
  
  */
  function renderMsg(_, data){
    var msgItemTpl = $('#msgItemTpl');
    log._log(data);
    $('.chat-container').append(_.template(msgItemTpl.html())({list: data}));

    //$('body')[0].scrollTop = $('.jsService').height();
    
    //$('body')[0].scrollTop = $('.chat-container').height() + parseFloat($('.chat-container').css('padding-top')) + parseFloat($('.chat-container').css('padding-bottom')) - $(window).height();

    $('body')[0].scrollTop = $('.jsService').height()-$(window).height();

  }
  /*
    文字信息URL处理
  */
  function setUrl(str){
    /*
      验证是否带有请求头正则
    */
    var reg = /(http:\/\/|https:\/\/)/g;
    /*
      提取URL正则
    */
    var reg1 = /((http:\/\/|https:\/\/)(((\w|=|\?|\/|&|-)+)(\.)((\.|\w|=|\?|\/|&|-)+)))/g;
    var reg2 = /((\w|=|\?|\/|&|-)+)(\.)((\.|\w|=|\?|\/|&|-)+)/g;
    if (reg2.test(str)) {
      if (!reg.test(str)) {
        str = str.replace(str.match(reg2)[0], '<a class="url-style" href="' + "http://" + str.match(reg2)[0] + '">' + str.match(reg2)[0] + '</a>');
      }else{
        str = str.replace(reg1, '<a class="url-style" href="$1">$1</a>');
      }
    }

    log._log(str);
    return str;
  }

  /*
    图片延时加载
  */

  function imgDefer(){
    var isDeferr = $('[data-deferr]').data('deferr');
    var doms = $('[data-deferr]');

    doms.each(function(index, el) {
      if (isDeferr != 1) {
        return false;
      }
      var self = this;
      var imgUrl = $(self).data('url');

      var img = new Image();

        img.onload = function(){
          $(self).parent().removeClass('img-start');
          $(self).attr({
            src : imgUrl
          });
          
          if (img.height < 600) {
            $(self).parent().css({
              height : 'auto'
            });
          }
        };

        img.src = imgUrl;
    });

  }

});